_ = require 'underscore'
async =  require 'async'

textModel = require './otc_sypz_date_model'
PageUtils =  require '../utils/page_util'

textServ =

  #获取查询条件
  getQuery: (params) ->
    tmpParams = {}
    if params
      query = params?.query or null
      if query
        for key, value of query
          if '' isnt value
            tmpParams[key] = value
    return tmpParams

  # 查询
  query : (params, cbf) ->
    query = @.getQuery params
    return PageUtils.pageQuery textModel, query, params.sorts, params.pageSize, params.pageNum, cbf

  # 删除
  remove : (params, cbf) ->
    params = {} if !params
    textModel.remove params, (err, res) ->
      if err
        return cbf err, null
      else
        return cbf null, res

  # 单个保存/修改
  save : (obj, cbf) ->
    if not obj or _.isEmpty obj
      return cbf '保存的记录不能为空！', null
    um = new textModel obj
    query = {_id : obj._id}

    textModel.find query, (err, res) ->
      if err
        return cbf err, null
      else
        # 存在，执行更新
        if res and res.length > 0

          textModel.findOneAndUpdate query, {$set: obj}, (err, rows) ->
            if err
              return cbf err, null
            else
              return cbf null, rows

        # 不存在，执行创建
        else
          um.save (err, rows) ->
            if err
              return cbf err, null
            else
              return cbf null, rows

module.exports = textServ